<?php

require_once(dirname(__FILE__)."/../../tests/test_helper.php");
require_once(dirname(__FILE__)."/../active_record.module");

//make these attributes public here so that we can test them
class BankTeller extends ActiveRecord {
	public $idColumn;
	public $tableName;
	public static $tableInformation;
	public function columnSQL($prefix=false){
		return parent::columnSQL($prefix);
	}
}
class Accountant extends ActiveRecord {
	public $idColumn = 'uid';
	public $tableName = 'something_strange';
}

class ActiveRecordTest extends UnitTestCase {
	function setUp(){
		$query = <<<HEREDOC
		 CREATE TABLE IF NOT EXISTS bank_tellers (
	        id int unsigned NOT NULL PRIMARY KEY,
	        name varchar(255) NOT NULL default ''
	     );
HEREDOC;
	  	db_query($query);
	  	$query = <<<HEREDOC
		 CREATE TABLE IF NOT EXISTS something_strange (
	        id int unsigned NOT NULL auto_increment PRIMARY KEY,
	        name varchar(255) NOT NULL default ''
	     );
HEREDOC;
  		db_query($query);
	}
	function tearDown(){
		db_query("DROP table bank_tellers");
  		db_query("DROP table something_strange");
	}
  function testSetColumnNames(){
  	
  	$a = new BankTeller();
  	$this->assertEqual($a->idColumn,'id');
  	$this->assertEqual($a->tableName,'bank_tellers');
  	$b = new Accountant();
  	$this->assertEqual($b->idColumn,'uid');
  	$this->assertEqual($b->tableName,'something_strange');
 	$this->assertEqual($a->columnNames(),array('id','name'));
  	
  }
  
  function testGenerateFindSQL(){
  	$a = new BankTeller();
  	$this->assertEqual($a->columnSQL('pf'),"bank_tellers.id as pf_id,bank_tellers.name as pf_name FROM {bank_tellers}");
  }
  
  function testGetAttributeSetAttribute(){
  	$a = new BankTeller(array('name' => 'Dan'));
  	$this->assertTrue($a->name == 'Dan');
  	$a->name = "A new name";
  	$this->assertEqual($a->name,"A new name");
  }
  function testCreateAndUpdate(){
  	$a = new BankTeller(array('name' => 'Dan'));
  	$this->assertTrue($a->save());
  	$this->assertTrue(intval($a->id) > 0, "$a->id should be greater than 0");
  	$initialId = $a->id;
  	$a->name = 'Another Name';
  	$a->save();
  	$this->assertEqual($a->id,$initialId);
  	$res = db_query("SELECT * FROM bank_tellers");
  	$this->assertEqual(db_num_rows($res),1,"Should only be one record in the database but there are ".db_num_rows($res));
  }
  function testFind(){
  	$a = new BankTeller(array('name' => 'Dan'));
  	$this->assertTrue($a->save());
  	$res = $a->find('all');
  	$this->assertEqual(sizeof($res),1,"Should be one row");
  	$b = $res[0];
  	$this->assertEqual($b,$a);
  }
}


?>
